// 检查MySQL服务状态的工具
const { exec } = require('child_process');
const os = require('os');

function checkMySQLService() {
  console.log('🔍 检查MySQL服务状态...\n');
  
  const platform = os.platform();
  let command;
  
  if (platform === 'win32') {
    // Windows系统
    command = 'sc query mysql || sc query mysql80 || sc query "MySQL80"';
  } else if (platform === 'darwin') {
    // macOS系统
    command = 'brew services list | grep mysql || launchctl list | grep mysql';
  } else {
    // Linux系统
    command = 'systemctl status mysql || systemctl status mysqld || service mysql status';
  }
  
  exec(command, (error, stdout, stderr) => {
    if (error) {
      console.log('❌ MySQL服务未运行或未找到');
      console.log('\n📋 解决方案:');
      
      if (platform === 'win32') {
        console.log('Windows系统:');
        console.log('1. 打开"服务"管理器 (services.msc)');
        console.log('2. 找到MySQL服务并启动');
        console.log('3. 或者以管理员身份运行命令: net start mysql');
        console.log('4. 如果没有安装MySQL，请下载安装: https://dev.mysql.com/downloads/mysql/');
      } else if (platform === 'darwin') {
        console.log('macOS系统:');
        console.log('1. 使用Homebrew启动: brew services start mysql');
        console.log('2. 或者手动启动: sudo /usr/local/mysql/support-files/mysql.server start');
      } else {
        console.log('Linux系统:');
        console.log('1. 启动服务: sudo systemctl start mysql');
        console.log('2. 或者: sudo service mysql start');
      }
      
      console.log('\n🔧 安装MySQL后，请确保:');
      console.log('- 设置root用户密码');
      console.log('- 更新.env文件中的DB_PASSWORD');
      console.log('- 重新运行初始化脚本');
      
    } else {
      console.log('✅ MySQL服务状态:');
      console.log(stdout);
      
      // 尝试连接测试
      testConnection();
    }
  });
}

async function testConnection() {
  const mysql = require('mysql2/promise');
  require('dotenv').config();
  
  try {
    console.log('\n🔗 尝试连接数据库...');
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'localhost',
      port: process.env.DB_PORT || 3306,
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || ''
    });
    
    console.log('✅ 数据库连接成功！');
    await connection.end();
    
    console.log('\n🚀 现在可以运行以下命令初始化数据库:');
    console.log('npm run init-db');
    
  } catch (error) {
    console.log('❌ 数据库连接失败:', error.message);
    
    if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('\n🔑 密码错误，请检查:');
      console.log('1. MySQL root用户密码是否正确');
      console.log('2. 更新.env文件中的DB_PASSWORD');
    } else if (error.code === 'ECONNREFUSED') {
      console.log('\n🔌 连接被拒绝，请检查:');
      console.log('1. MySQL服务是否已启动');
      console.log('2. 端口3306是否被占用');
      console.log('3. 防火墙设置');
    }
  }
}

if (require.main === module) {
  checkMySQLService();
}

module.exports = checkMySQLService;